package com.qili.service.it.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.base.BaseDict;
import com.qili.entity.base.Col;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.sys.SysLog;
import com.qili.mapper.search.ItFormMapper;
import com.qili.mapper.supervisor.SupervisorFileMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.SupervisorProjectFormsService;
import com.qili.util.BeanUtil;
import com.qili.util.CommonUtil;
import com.qili.util.DateUtil;
import com.qili.util.ReType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;
import java.io.File;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxiaopeng
 * @date 2021/4/2
 * @description     论文表单具体业务类
 */
@Service("LunWenFormService")
public class LunWenFormServiceImpl extends FormBaseServiceImpl{

    public static final Integer FILE_COUNT = 3;

    @Autowired
    ItFormMapper itFormMapper;
    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;
    @Autowired
    BaseDictService baseDictService;

    @Autowired
    SysLogMapper sysLogMapper;

    @Autowired
    private SupervisorFileMapper supervisorFileMapper;

    /**
     * 论文统计,点击数字详情页的table数据:
     * @param formInfo
     * @param index
     * @return
     */
    public ReType getFormStatisticsDetail(SupervisorProjectFromsDTO formInfo, String index,String page,String limit) {
        Page<SupervisorProjectFromsDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<Map<String,String>> resultMap = itFormMapper.getLunWenDetail(formInfo);
        return new ReType(tPage.getTotal(),resultMap);

    }

    public void saveFormData(SupervisorProjectFromsDTO forms, boolean ifNew) {
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //把原来的删除:
            SupervisorProjectFormsData formsData = new SupervisorProjectFormsData();
            formsData.setSpfId(forms.getSpfId());
            formsDataService.delete(formsData);
        }
        //通知书
        SupervisorProjectFormsData spfd=new SupervisorProjectFormsData();
        ArrayList<String> strList1 = forms.getStrList1();
        if(CollectionUtil.isNotEmpty(strList1)){
            for(int i=0;i<strList1.size();i++){
                spfd.setSpfdataId(IdUtil.simpleUUID());
                spfd.setSpfId(forms.getSpfId());
                spfd.setData1(strList1.get(i));
                spfd.setTableIndex(i);
                spfd.setData10("zhuozhe");
                formsDataService.insertSelective(spfd);
            }
        }
    }

    /**
     * 保存表单文件
     * @param forms
     * @param ifNew
     */
    public void saveFormFile(SupervisorProjectFromsDTO forms, boolean ifNew) {
        ArrayList<String> fileIds = new ArrayList<String>();
        //通知书
        ArrayList<String> tongZhiShuFileIds = forms.getStrList2();
        //论文原稿
        ArrayList<String> lunWenYuanGaoFileIds = forms.getStrList3();
        //期刊扫描件
        ArrayList<String> QiKanSaoMiaoJianFileIds = forms.getStrList4();
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //编辑表单页面不需要移动文件，只是操作删除数组:
            ArrayList<String> strList9 = forms.getStrList9();
            if(CollectionUtil.isNotEmpty(strList9)){
                for(String delFileId:strList9){
                    //设置为回收站状态:
                    SupervisorFile delFile = new SupervisorFile();
                    delFile.setId(delFileId);
                    delFile.setDeleteState("2");
                    delFile.setDeleteUser(CommonUtil.getUserId());
                    delFile.setDeleteDate(DateUtil.getCurrentDateString());
                    dicService.updateByPrimaryKeySelective(delFile);
                    SupervisorFile supervisorFile = supervisorFileMapper.selectByPrimaryKey(delFileId);
                    if(supervisorFile!=null){
                        insertFileLog(supervisorFile.getFileName());
                    }
                }
            }
        }else{
            //合并:
            if(CollectionUtil.isNotEmpty(tongZhiShuFileIds)){
                fileIds.addAll(tongZhiShuFileIds);
            }
            if(CollectionUtil.isNotEmpty(lunWenYuanGaoFileIds)){
                fileIds.addAll(lunWenYuanGaoFileIds);
            }
            if(CollectionUtil.isNotEmpty(QiKanSaoMiaoJianFileIds)){
                fileIds.addAll(QiKanSaoMiaoJianFileIds);
            }
            //这里是新建表单逻辑:
            //新建表单核心文件夹:
            String formCode = forms.getSpfF30();
            FormType formType = FormType.getFormType(formCode);
            //生成表单核心文件夹路径：（例如:/书著/2021_001_xx书著）
            //该方法执行后,会把核心文件设置为formDto的Obj1对象
            createCenterDic(forms);
            SupervisorFile centFile = (SupervisorFile) forms.getObj1();
            if(CollectionUtil.isNotEmpty(fileIds)){
                //这里面存放的是临时文件id:
                for(String shuzhuFileId : fileIds){
                    SupervisorFileTemp supervisorFileTemp = fileTempService.selectByPrimaryKey(shuzhuFileId);
                    //1.移动操作系统文件 newFile为移动后的文件
                    File newFile = moveTempFile(supervisorFileTemp, forms);
                    //2.复制数据到正式文件表
                    //更改url
                    supervisorFileTemp.setUrl(newFile.getPath());
                    SupervisorFile newSupervisorFile = new SupervisorFile();
                    BeanUtil.copyNotNullBean(supervisorFileTemp,newSupervisorFile);
                    newSupervisorFile.setZskfileType("2");
                    newSupervisorFile.setDeleteState("1");
                    //表单中的每一个文件都指向该核心文件
                    newSupervisorFile.setLinkId(centFile.getId());
                    fileService.insertFile(newSupervisorFile,(SupervisorFile) forms.getObj1());
                    //3.删除临时文件表
                    fileTempService.deleteByPrimaryKey(shuzhuFileId);
                }
            }
        }
    }

    public void insertFileLog(String filename) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("DEL");
        sysLog.setText("删除文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser user = CommonUtil.getUser();
        sysLog.setUserName(user.getUsername());
        sysLogMapper.insert(sysLog);
    }

    /**
     * 获取表单数据
     * @param formTypeCode
     * @param formDto
     * @param model
     */
    public void getFormData(String formTypeCode, SupervisorProjectFromsDTO formDto, Model model) {
        Example zhubianExample = new Example(SupervisorProjectFormsData.class);
        zhubianExample.and().andEqualTo("data10","zhuozhe")
                .andEqualTo("spfId",formDto.getSpfId());
        zhubianExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select1 = formsDataService.selectByExample(zhubianExample);
        if(CollectionUtil.isNotEmpty(select1)){
            select1.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
                model.addAttribute("zhuozhe",select1);
        }
    }

    private List<SupervisorProjectFormsData> getFormData(String formTypeCode,SupervisorProjectFromsDTO formDto){
        Example zhubianExample = new Example(SupervisorProjectFormsData.class);
        zhubianExample.and().andEqualTo("data10","zhuozhe")
                .andEqualTo("spfId",formDto.getSpfId());
        zhubianExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select1 = formsDataService.selectByExample(zhubianExample);
        if(CollectionUtil.isNotEmpty(select1)){
            select1.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
        }
        return select1;
    }


    public List<String> getAuthorIndexListTz(SupervisorProjectFromsDTO formInfo) {
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            formInfo.setSpfF1("%"+formInfo.getSpfF1()+"%");
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF4())){
            formInfo.setSpfF4("%"+formInfo.getSpfF4()+"%");
        }
        return itFormMapper.getAuthorIndexListTz(formInfo);
    }

    /**
     * 统计时,根据条件,查询符合条件的作者最大数:
     * @param formInfo
     * var jsondata = {
     * 			spfF1:lwmc,
     * 			spfF2:author,
     * 			spfF5:projectName,
     * 			spfF8:jkrqStart,
     * 			spfF9:jkrqEnd
     *                };
     * @return
     */
    public List<String> getAuthorIndexListTj(SupervisorProjectFromsDTO formInfo) {
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            formInfo.setSpfF1(formInfo.getSpfF1().trim());
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF2())){
            formInfo.setSpfF2(formInfo.getSpfF2().trim());
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF5())){
            formInfo.setSpfF5(formInfo.getSpfF5().trim());
        }
        List<String> authorIndexListTj = itFormMapper.getAuthorIndexListTj(formInfo);
        return authorIndexListTj;
    }

    public ReType selectFormBook(SupervisorProjectFromsDTO formInfo, String page, String limit) {
        Example example = new Example(SupervisorProjectForms.class);
        example.and().andEqualTo("spfF30",formInfo.getSpfF30());
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            example.and().andLike("spfF1","%"+formInfo.getSpfF1()+"%");
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF3()) && !"000".equals(formInfo.getSpfF3())){
            example.and().andEqualTo("spfF3",formInfo.getSpfF3());
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF4())){
            example.and().andLike("spfF4","%"+formInfo.getSpfF4()+"%");
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF8())){
            example.and().andGreaterThanOrEqualTo("spfF2",formInfo.getSpfF8());
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF9())){
            example.and().andLessThanOrEqualTo("spfF2",formInfo.getSpfF9());
        }
        Example.Criteria criteria = example.createCriteria();
        criteria.andCondition("  exists (select  1  from  supervisor_file  where link_id=spf_id   and  delete_state='1')");
        example.and(criteria);
        example.setOrderByClause("create_date desc");
        Page<SupervisorProjectFromsDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupervisorProjectForms> supervisorProjectForms = supervisorProjectFormsService.selectByExample(example);
        List<Map<String,Object>> formDto = new ArrayList<Map<String,Object>>();
        if(CollectionUtil.isNotEmpty(supervisorProjectForms)){
            formDto = getFormDto(formInfo.getSpfF30(), supervisorProjectForms);
        }
        return new ReType(tPage.getTotal(),formDto);
    }

    private List<Map<String,Object>> getFormDto(String formTypeCode,List<SupervisorProjectForms> supervisorProjectForms) {
        List<Map<String,Object>> formsDtoList = new ArrayList<Map<String,Object>>();
        for(int i=0;i<supervisorProjectForms.size();i++){
            SupervisorProjectForms aForm = supervisorProjectForms.get(i);
            SupervisorProjectFromsDTO aDto = changeToDto(aForm);
            Map map = changeFormToMap(aForm);
            map.put("fileInd",(i+1)+"");
            List<SupervisorProjectFormsData> formDataList = getFormData(formTypeCode, aDto);
            if(CollectionUtil.isNotEmpty(formDataList)){
                for(SupervisorProjectFormsData formData : formDataList){
                    map.put(""+formData.getTableIndex(),formData.getData1());
                }
            }
            setFormFiles(formTypeCode,aDto);
            for(int b=1;b<FILE_COUNT+1;b++){
                try{
                    Field declaredField = aDto.getClass().getDeclaredField("fileList" + b);
                    declaredField.setAccessible(true);
                    Object o = declaredField.get(aDto);
                    map.put("fileList"+b,o);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            formsDtoList.add(map);
        }
        return formsDtoList;
    }

    /**
     * 获取统计表格表头
     * @param formTypeCode
     * @param formInfo
     * @param index
     * var jsondata = {
     * 			spfF1:lwmc,
     * 			spfF2:author,
     * 			spfF5:projectName,
     * 			spfF8:jkrqStart,
     * 			spfF9:jkrqEnd
     *                };
     * @return
     */
    @Override
    public List<Col> getFormStatisticstableHead(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index) {
        if(StringUtils.isBlank(index)){
            return null;
        }
        List<Col> colArrayList = new ArrayList<>();
        if("0".equals(index)) {
            //按照人统计情况:
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //姓名:
            colArrayList.add(new Col("author","姓名","10%",null,null,null,false));
            //总篇数:
            colArrayList.add(new Col("totalCount","总篇数","10%",null,
                    "color: dodgerblue;cursor: pointer","showCountDetail",false));
            //根据条件获取最大作者数:
            List<String> authorIndexListTj = getAuthorIndexListTj(formInfo);
            if(CollectionUtil.isNotEmpty(authorIndexListTj)){
                for(int i=0;i<authorIndexListTj.size();i++){
                    if(i > 5){
                        colArrayList.add(new Col("otherAuthor","其他作者数","10%",null,null,null,false));
                        break;
                    }
                    String tableIndex = authorIndexListTj.get(i);
                    //第 n 作者数:
                    colArrayList.add(new Col(tableIndex+"","第"+(Integer.valueOf(tableIndex)+1)+"作者数","10%",null,null,null,false));

                }

            }
            //查询所有的期刊类型:
            BaseDict select = new BaseDict();
            select.setBadtTypecode("QKLX001");
            List<BaseDict> select1 = baseDictService.select(select);
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict aQklx : select1){
                    //每个期刊类型:
                    colArrayList.add(new Col(aQklx.getBadtCode(),aQklx.getBadtName()+"数","10%",null,null,null,false));
                }
            }
        }else if("1".equals(index)) {
            //按照挂项目统计情况:
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //挂项目名称
            colArrayList.add(new Col("projName","挂项目名称","25%",null,null,null,false));
            //总篇数:
            colArrayList.add(new Col("totalCount","总篇数","10%",null,null,null,false));
            //查询所有的期刊类型:
            BaseDict select = new BaseDict();
            select.setBadtTypecode("QKLX001");
            List<BaseDict> select1 = baseDictService.select(select);
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict aQklx : select1){
                    //每个期刊类型:
                    colArrayList.add(new Col(aQklx.getBadtCode(),aQklx.getBadtName()+"数","11%",null,null,null,false));
                }
            }
        }else if("2".equals(index)) {
            //按照论文名称统计
            //总篇数:
            colArrayList.add(new Col("totalCount","总篇数","20%",null,null,null,false));
            //查询所有的期刊类型:
            BaseDict select = new BaseDict();
            select.setBadtTypecode("QKLX001");
            List<BaseDict> select1 = baseDictService.select(select);
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict aQklx : select1){
                    //每个期刊类型:
                    colArrayList.add(new Col(aQklx.getBadtCode(),aQklx.getBadtName()+"数","16%",null,null,null,false));
                }
            }
        }else if("3".equals(index)){
            //按时间统计：
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //年份:
            colArrayList.add(new Col("year","年份","10%",null,null,null,false));
            //论文总篇数:
            colArrayList.add(new Col("totalCount","论文总篇数","20%",null,null,null,false));
            //查询所有的期刊类型:
            BaseDict select = new BaseDict();
            select.setBadtTypecode("QKLX001");
            List<BaseDict> select1 = baseDictService.select(select);
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict aQklx : select1){
                    //每个期刊类型:
                    colArrayList.add(new Col(aQklx.getBadtCode(),aQklx.getBadtName()+"数","20%",null,null,null,false));
                }
            }
        }
        return colArrayList;
    }

    /**
     * 获取论文统计表格数据:
     *
     * @param index 0:按计划类别统计    1:按项目级别统计    2:按项目负责人统计    3:按人员统计
     * @param formInfo
     * var jsondata = {
     * 			spfF1:lwmc,
     * 			spfF2:author,
     * 			spfF5:projectName,
     * 			spfF8:jkrqStart,
     * 			spfF9:jkrqEnd
     *                };
     * @return
     */
    @Override
    public ReType selectFormStatisticsTableData(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index, String page, String limit) {
        if(StringUtils.isNotBlank(index)){
            if("0".equals(index)){
                if(StringUtils.isNotBlank(formInfo.getSpfF2())){
                    formInfo.setSpfF2(formInfo.getSpfF2().trim());
                }
            }
            if("1".equals(index)){
                if(StringUtils.isNotBlank(formInfo.getSpfF5())){
                    formInfo.setSpfF5(formInfo.getSpfF5().trim());
                }
            }
        }
        Map paraMap = new HashMap();
        //查询所有的期刊类型:
        BaseDict select = new BaseDict();
        select.setBadtTypecode("QKLX001");
        List<BaseDict> select1 = baseDictService.select(select);
        if(CollectionUtil.isNotEmpty(select1)){
            paraMap.put("qklxList",select1);
        }
        if("0".equals(index)){
            //先根据条件,获取作者下标集合
            List<String> tableIndexList = getAuthorIndexListTj(formInfo);
            if(CollectionUtil.isNotEmpty(tableIndexList)){
                List<String> authorLevelList = new ArrayList<>();
                for(int i=0;i<tableIndexList.size();i++){
                    if(i > 5){
                        paraMap.put("otherAuthor","1");
                        break;
                    }
                    authorLevelList.add(tableIndexList.get(i)+"");
                }
                paraMap.put("authorLevelList",authorLevelList);
            }
            if(CollectionUtil.isNotEmpty(select1)){
                paraMap.put("qklxList",select1);
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF2())){
                paraMap.put("author",formInfo.getSpfF2().trim());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF8())){
                paraMap.put("spfF8",formInfo.getSpfF8().trim());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF9())){
                paraMap.put("spfF9",formInfo.getSpfF9().trim());
            }
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getLunWenStatistics0(paraMap);
            //获取根据符合条件的年份列表:

            return new ReType(objects.getTotal(),resultMap);
        }else if("1".equals(index)){
            if(StringUtils.isNotBlank(formInfo.getSpfF5())){
                paraMap.put("spfF5",formInfo.getSpfF5().trim());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF8())){
                paraMap.put("spfF8",formInfo.getSpfF8().trim());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF9())){
                paraMap.put("spfF9",formInfo.getSpfF9().trim());
            }
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getLunWenStatistics1(paraMap);
            //获取根据符合条件的年份列表:

            return new ReType(objects.getTotal(),resultMap);
        }else if("2".equals(index)){
            if(StringUtils.isNotBlank(formInfo.getSpfF1())){
                paraMap.put("spfF1","%"+formInfo.getSpfF1().trim()+"%");
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF8())){
                paraMap.put("spfF8",formInfo.getSpfF8().trim());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF9())){
                paraMap.put("spfF9",formInfo.getSpfF9().trim());
            }
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getLunWenStatistics2(paraMap);
            //获取根据符合条件的年份列表:
            return new ReType(objects.getTotal(),resultMap);
        }else if("3".equals(index)){
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map<String,Object>> resultMap = itFormMapper.getLunWenStatistics3(paraMap);
            //获取根据符合条件的年份列表:
            return new ReType(objects.getTotal(),resultMap);
        }
        return null;
    }
}
